#include "doorbell_camera.h"
#include "doorbell_config.h"
#include "jpeg_decoder.h"

void doorbell_camera_init(void)
{
    // 生成配置
    camera_config_t camera_config = {
        .pin_pwdn = CAM_PWDN_PIN,
        .pin_reset = CAM_RESET_PIN,
        .pin_xclk = CAM_MCLK_PIN,
        .pin_sccb_sda = I2C_SDA_PIN,
        .pin_sccb_scl = I2C_SCL_PIN,
        .pin_d7 = CAM_D7_PIN,
        .pin_d6 = CAM_D6_PIN,
        .pin_d5 = CAM_D5_PIN,
        .pin_d4 = CAM_D4_PIN,
        .pin_d3 = CAM_D3_PIN,
        .pin_d2 = CAM_D2_PIN,
        .pin_d1 = CAM_D1_PIN,
        .pin_d0 = CAM_D0_PIN,
        .pin_vsync = CAM_VSYNC_PIN,
        .pin_href = CAM_HREF_PIN,
        .pin_pclk = CAM_PCLK_PIN,

        .xclk_freq_hz = 20000000,
        .ledc_timer = LEDC_TIMER_0,
        .ledc_channel = LEDC_CHANNEL_0,
        .pixel_format = PIXFORMAT_JPEG,
        .frame_size = FRAMESIZE_QVGA,
        .jpeg_quality = 10,
        .fb_count = 2,
        .fb_location = CAMERA_FB_IN_PSRAM,
        .grab_mode = CAMERA_GRAB_WHEN_EMPTY,
    };

    // 初始化摄像头
    ESP_ERROR_CHECK(esp_camera_init(&camera_config));
}

void doorbell_camera_deinit(void)
{
    ESP_ERROR_CHECK(esp_camera_deinit());
}

camera_fb_t *doorbell_camera_capture()
{
    return esp_camera_fb_get();
}

void doorbell_camera_release(camera_fb_t *fb)
{
    esp_camera_fb_return(fb);
}

void doorbell_camera_fb2rgb565(camera_fb_t *fb, void *rgb565_buf)
{
    esp_jpeg_image_cfg_t jpeg_cfg = {
        .indata = fb->buf,
        .indata_size = fb->len,
        .outbuf = rgb565_buf,
        .outbuf_size = LCD_WIDTH * LCD_HEIGHT * 2,
        .out_format = JPEG_IMAGE_FORMAT_RGB565,
        .out_scale = JPEG_IMAGE_SCALE_0,
        .flags.swap_color_bytes = 1,
    };

    esp_jpeg_image_output_t output_img = {};

    ESP_ERROR_CHECK(esp_jpeg_decode(&jpeg_cfg, &output_img));
}
